package com.ssy.lingxi.system.service.impl;

import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.constant.template.PageTemplateTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.template.api.feign.paas.PageTemplatePAASControllerFeign;
import com.ssy.lingxi.platform.template.api.model.dto.paas.PageTemplatePAASDTO;
import com.ssy.lingxi.system.common.CommonBooleanEnum;
import com.ssy.lingxi.system.dao.PageTemplateRepository;
import com.ssy.lingxi.system.dao.ShopConfigRepository;
import com.ssy.lingxi.system.dao.SiteRepository;
import com.ssy.lingxi.system.dto.request.CommonIdDTO;
import com.ssy.lingxi.system.entity.PageTemplate;
import com.ssy.lingxi.system.entity.ShopConfig;
import com.ssy.lingxi.system.entity.Site;
import com.ssy.lingxi.system.model.dto.template.*;
import com.ssy.lingxi.system.service.PageTemplateService;
import com.ssy.lingxi.system.utils.UserDetailsUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @menu 页面定制 - 模板管理 - 业务实现层
 * @author fhj
 * @version 2.0.0
 * @date 2020/07/17
 */
@Service
public class PageTemplateServiceImpl implements PageTemplateService {

    @Resource
    private PageTemplateRepository pageTemplateRepository;
    @Resource
    private UserDetailsUtil userDetailsUtil;
    @Resource
    private PageTemplatePAASControllerFeign pageTemplateControllerFeign;
    @Resource
    private SiteRepository siteRepository;
    @Resource
    private ShopConfigRepository shopConfigRepository;

    @Override
    @Transactional
    public Wrapper<Void> add(PageTemplateAddDTO dto, HttpServletRequest request) {
        //新增页面模板
        PageTemplate pageTemplate = new PageTemplate();
        BeanUtils.copyProperties(dto, pageTemplate);
        pageTemplate.setCreateRoleId(userDetailsUtil.getLoginUserDetails(request).getId());
        pageTemplateRepository.saveAndFlush(pageTemplate);

        //调用页面模板服务 -> 新增模板
        PageTemplatePAASDTO pageTemplatePAASDTO = new PageTemplatePAASDTO();
        BeanUtils.copyProperties(pageTemplate, pageTemplatePAASDTO);
        Wrapper<?> wrapper = pageTemplateControllerFeign.add(pageTemplatePAASDTO);
        if(wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            throw new BusinessException(ResponseCode.SERVICE_PLATFORM_TEMPLATE_ERROR);
        }

        return Wrapper.success();
    }

    @Override
    @Transactional
    public Wrapper<Void> update(PageTemplateUpdateDTO dto, HttpServletRequest request) {
        //根据ID获取模板详情
        PageTemplate pageTemplate = pageTemplateRepository.findById(dto.getId()).orElse(null);
        if(pageTemplate == null) {
            return Wrapper.fail(ResponseCode.NO_TEMPLATE_FOUND_BASED_ON_ID);
        }

        //更新
        pageTemplate.setTemplateName(dto.getTemplateName());
        pageTemplate.setTemplateDescribe(dto.getTemplateDescribe());
        pageTemplate.setTemplatePicUrl(dto.getTemplatePicUrl());
        pageTemplate.setFileName(dto.getFileName());
        pageTemplate.setUpdateTime(System.currentTimeMillis());
        pageTemplate.setCreateRoleId(userDetailsUtil.getLoginUserDetails(request).getId());
        pageTemplateRepository.saveAndFlush(pageTemplate);

        //调用页面模板服务 -> 修改模板
        PageTemplatePAASDTO pageTemplatePAASDTO = new PageTemplatePAASDTO();
        BeanUtils.copyProperties(pageTemplate, pageTemplatePAASDTO);
        Wrapper<?> wrapper = pageTemplateControllerFeign.update(pageTemplatePAASDTO);
        if(wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            throw new BusinessException(ResponseCode.SERVICE_PLATFORM_TEMPLATE_ERROR);
        }

        return Wrapper.success();
    }

    @Override
    public Wrapper<List<PageTemplate>> all(PageTemplateAllDTO dto) {
        List<PageTemplate> pageTemplateList = pageTemplateRepository.findAllByType(dto.getType(), Sort.by("createTime").descending());
        return Wrapper.success(pageTemplateList);
    }

    @Override
    public Wrapper<PageTemplate> details(CommonIdDTO dto) {
        return Wrapper.success(pageTemplateRepository.findById(dto.getId()).orElse(null));
    }

    @Override
    @Transactional
    public Wrapper<Void> use(PageTemplateUseDTO dto, HttpServletRequest request) {
        //根据ID获取模板详情
        PageTemplate pageTemplate = pageTemplateRepository.findById(dto.getId()).orElse(null);
        if(pageTemplate == null) {
            return Wrapper.fail(ResponseCode.NO_TEMPLATE_FOUND_BASED_ON_ID);
        }

        //站点、商城
        Site site = siteRepository.findById(dto.getSiteId()).orElse(new Site());
        ShopConfig shop = new ShopConfig();

        //如果为企业商城模板、店铺模板、渠道模板、自营商城模板，那需要校验
        if(PageTemplateTypeEnum.checkShopIdTemplate(dto.getType())) {
            //商城ID校验
            if(dto.getShopId() == null) {
                return Wrapper.fail(ResponseCode.PURCHASE_SHOP_NOT_EXIST);
            }
            //获取商城
            shop = shopConfigRepository.findById(dto.getShopId()).orElse(null);
            if(shop == null) {
                return Wrapper.fail(ResponseCode.NO_SHOP_FOUND_BASED_ON_ID);
            }
            //环境校验
            if(!shop.getEnvironment().equals(pageTemplate.getEnvironment())) {
                return Wrapper.fail(ResponseCode.TEMPLATE_ENVIRONMENT_AND_MALL_ENVIRONMENT_INCOMPATIBLE);
            }
            //企业商城模板校验
            if(dto.getType().equals(PageTemplateTypeEnum.MALL.getCode())) {
                if(!shop.getType().equals(ShopTypeEnum.ENTERPRISE.getCode())) {
                    return Wrapper.fail(ResponseCode.ONLY_THE_BUSINESS_MALL_CAN_BE_SELECTED);
                }
                if(!shop.getSelf().equals(CommonBooleanEnum.NO.getCode())) {
                    return Wrapper.fail(ResponseCode.NEED_TO_BE_A_NON_SELF_OPERATED_MALL);
                }
            }
            //会员店铺模板校验
            if(dto.getType().equals(PageTemplateTypeEnum.SHOP.getCode())) {
                if(!shop.getType().equals(ShopTypeEnum.ENTERPRISE.getCode())) {
                    return Wrapper.fail(ResponseCode.ONLY_THE_BUSINESS_MALL_CAN_BE_SELECTED);
                }
                if(!shop.getSelf().equals(CommonBooleanEnum.NO.getCode())) {
                    return Wrapper.fail(ResponseCode.NEED_TO_BE_A_NON_SELF_OPERATED_MALL);
                }
            }
            //渠道商城模板校验
            if(dto.getType().equals(PageTemplateTypeEnum.CHANNEL.getCode())) {
                if(!ShopTypeEnum.checkChannelOrChannelSelf(shop.getType())) {
                    return Wrapper.fail(ResponseCode.CAN_ONLY_CHOOSE_CHANNEL_MALL_OR_CHANNEL_OWNED_MALL);
                }
            }
            //自营商城模板校验
            if(dto.getType().equals(PageTemplateTypeEnum.SELF.getCode())) {
                if(!shop.getType().equals(ShopTypeEnum.ENTERPRISE.getCode())) {
                    return Wrapper.fail(ResponseCode.ONLY_THE_BUSINESS_MALL_CAN_BE_SELECTED);
                }
                if(!shop.getSelf().equals(CommonBooleanEnum.YES.getCode())) {
                    return Wrapper.fail(ResponseCode.NEED_TO_BE_SELF_OPERATED_MALL);
                }
            }
        }

        //更新模板的站点ID、商城ID、站点名称、商城名称、商城类型、商城属性
        pageTemplate.setSiteId(dto.getSiteId());
        pageTemplate.setShopId(dto.getShopId());
        pageTemplate.setSiteName(site.getName());
        pageTemplate.setShopName(shop.getName());
        pageTemplate.setShopType(shop.getType());
        pageTemplate.setProperty(shop.getProperty());

        //如果为会员店铺模板、渠道商城模板、活动模板、自营商城模板，那需要修改'是否允许使用'字段，且'状态'字段也跟着同步
        if(PageTemplateTypeEnum.checkAllowTemplate(dto.getType())) {
            pageTemplate.setAllow(dto.getAllow());
            pageTemplate.setStatus(dto.getAllow());
        }

        //如果为平台首页模板、企业商城模板、商品模板，那需要修改'状态'字段为已使用，且'是否允许使用'字段也跟着同步
        if(PageTemplateTypeEnum.checkStatusTemplate(dto.getType())) {
            pageTemplate.setAllow(CommonConstant.State.STATE_START);
            pageTemplate.setStatus(CommonConstant.State.STATE_START);

            //将同站点同环境同类型的模板全部改为不可用，如果是企业商城还需加上同商城
            List<PageTemplate> pageTemplateList;
            if(dto.getType().equals(PageTemplateTypeEnum.MALL.getCode())) {
                pageTemplateList = pageTemplateRepository.findAllBySiteIdAndShopIdAndEnvironmentAndType(
                        dto.getSiteId(),
                        dto.getShopId(),
                        dto.getEnvironment(),
                        dto.getType()
                );
            }else {
                pageTemplateList = pageTemplateRepository.findAllBySiteIdAndEnvironmentAndType(
                        dto.getSiteId(),
                        dto.getEnvironment(),
                        dto.getType()
                );
            }
            //同时排除要修改的模板
            pageTemplateList.stream().filter(a -> !a.getId().equals(dto.getId())).forEach(a -> {
                a.setStatus(CommonBooleanEnum.NO.getCode());
                a.setAllow(CommonBooleanEnum.NO.getCode());
            });
            pageTemplateRepository.saveAll(pageTemplateList);
        }

        //更新模板
        pageTemplateRepository.saveAndFlush(pageTemplate);

        //调用页面模板服务 -> 使用模板
        PageTemplatePAASDTO pageTemplatePAASDTO = new PageTemplatePAASDTO();
        BeanUtils.copyProperties(pageTemplate, pageTemplatePAASDTO);
        Wrapper<?> wrapper = pageTemplateControllerFeign.use(pageTemplatePAASDTO);
        if(wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            throw new BusinessException(ResponseCode.SERVICE_PLATFORM_TEMPLATE_ERROR);
        }

        return Wrapper.success();
    }

    @Override
    public Wrapper<PageTemplate> inUseTemplate(PageTemplateInUseDTO dto) {
        //针对平台首页模板、企业商城模板、商品描述模板
        PageTemplate pageTemplate = pageTemplateRepository.findBySiteIdAndShopIdAndTypeAndStatus(
                dto.getSiteId(),
                dto.getShopId(),
                dto.getType(),
                CommonBooleanEnum.YES.getCode()
        );
        return Wrapper.success(pageTemplate);
    }
}
